package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/models"
	"time"

	"github.com/beego/beego/v2/server/web"
)

// CouponActivityController 优惠活动管理控制器
type CouponActivityController struct {
	web.Controller
}

// CouponActivityListRequest 优惠活动列表请求参数
type CouponActivityListRequest struct {
	Page      int    `json:"page" form:"page"`
	PageSize  int    `json:"pageSize" form:"pageSize"`
	Name      string `json:"name" form:"name"`
	Type      string `json:"type" form:"type"`
	Status    string `json:"status" form:"status"`
	StartTime int64  `json:"start_time" form:"start_time"`
	EndTime   int64  `json:"end_time" form:"end_time"`
}

// CouponActivityCreateRequest 创建优惠活动请求参数
type CouponActivityCreateRequest struct {
	Name              string  `json:"name"`
	Type              int     `json:"type"`
	Description       string  `json:"description"`
	StartTime         int64   `json:"start_time"`
	EndTime           int64   `json:"end_time"`
	MinAmount         float64 `json:"min_amount"`
	DiscountAmount    float64 `json:"discount_amount,omitempty"`
	DiscountRate      float64 `json:"discount_rate"`
	CouponIds         []int64 `json:"coupon_ids"`
	Status            int     `json:"status"`
	ApplicableType    int8    `json:"applicable_type"`
	ApplicableIds     string  `json:"applicable_ids"`
	AvailableWeekdays string  `json:"available_weekdays"`
	AvailableTimes    string  `json:"available_times"`
}

// CouponActivityUpdateRequest 更新优惠活动请求参数
type CouponActivityUpdateRequest struct {
	Id                int64   `json:"id"`
	Name              string  `json:"name"`
	Type              int     `json:"type"`
	Description       string  `json:"description"`
	StartTime         int64   `json:"start_time"`
	EndTime           int64   `json:"end_time"`
	MinAmount         float64 `json:"min_amount"`
	DiscountAmount    float64 `json:"discount_amount,omitempty"`
	DiscountRate      float64 `json:"discount_rate"`
	CouponIds         []int64 `json:"coupon_ids"`
	Status            int     `json:"status"`
	ApplicableType    int8    `json:"applicable_type"`
	ApplicableIds     string  `json:"applicable_ids"`
	AvailableWeekdays string  `json:"available_weekdays"`
	AvailableTimes    string  `json:"available_times"`
}

// List 获取优惠活动列表
func (c *CouponActivityController) List() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取请求参数
	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.GetString("pageSize"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	name := c.GetString("name")
	activityType, _ := c.GetInt("type", -1)
	status, _ := c.GetInt("status", -1)
	startTime, _ := c.GetInt64("start_time", -1)
	endTime, _ := c.GetInt64("end_time", -1)

	// 添加新的时间范围过滤条件
	startTimeLte, _ := c.GetInt64("start_time_lte", -1)
	endTimeGte, _ := c.GetInt64("end_time_gte", -1)
	startTimeGt, _ := c.GetInt64("start_time_gt", -1)
	endTimeLt, _ := c.GetInt64("end_time_lt", -1)

	// 构建过滤条件
	filters := make(map[string]interface{})
	if name != "" {
		filters["name"] = name
	}
	if activityType != -1 {
		filters["type"] = activityType
	}
	if status != -1 {
		filters["status"] = status
	}

	// 处理时间范围
	if startTime != -1 {
		filters["start_time"] = startTime
	}
	if endTime != -1 {
		filters["end_time"] = endTime
	}

	// 添加新的时间范围过滤条件
	if startTimeLte != -1 {
		filters["start_time_lte"] = startTimeLte
	}
	if endTimeGte != -1 {
		filters["end_time_gte"] = endTimeGte
	}
	if startTimeGt != -1 {
		filters["start_time_gt"] = startTimeGt
	}
	if endTimeLt != -1 {
		filters["end_time_lt"] = endTimeLt
	}

	// 加盟商权限过滤
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	// 查询优惠活动列表
	activities, total, err := models.GetCouponActivityList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠活动列表失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取优惠活动列表成功",
		"data": map[string]interface{}{
			"list":  activities,
			"total": total,
		},
	}
	c.ServeJSON()
}

// GetOne 获取单个优惠活动详情
func (c *CouponActivityController) GetOne() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取优惠活动ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的优惠活动ID",
		}
		c.ServeJSON()
		return
	}

	// 获取优惠活动信息
	activity, err := models.GetCouponActivityById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠活动信息失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && activity.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权访问此优惠活动",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取优惠活动信息成功",
		"data":    activity,
	}
	c.ServeJSON()
}

// Create 创建优惠活动
func (c *CouponActivityController) Create() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req CouponActivityCreateRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 处理优惠券ID
	var couponIdsStr string
	if req.Type == 3 && len(req.CouponIds) > 0 {
		couponIdsBytes, err := json.Marshal(req.CouponIds)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "处理优惠券ID失败",
			}
			c.ServeJSON()
			return
		}
		couponIdsStr = string(couponIdsBytes)
	}

	// 创建优惠活动
	activity := &models.CouponActivity{
		Name:              req.Name,
		Type:              req.Type,
		Description:       req.Description,
		StartTime:         req.StartTime,
		EndTime:           req.EndTime,
		MinAmount:         req.MinAmount,
		DiscountAmount:    req.DiscountAmount,
		DiscountRate:      req.DiscountRate,
		CouponIds:         couponIdsStr,
		Status:            req.Status,
		ApplicableType:    req.ApplicableType,
		ApplicableIds:     req.ApplicableIds,
		AvailableWeekdays: req.AvailableWeekdays,
		AvailableTimes:    req.AvailableTimes,
	}

	// 设置加盟商ID
	activity.FranchiseId = permResult.Admin.FranchiseId

	// 设置创建者信息
	activity.CreatedBy = permResult.Admin.Username
	activity.UpdatedBy = permResult.Admin.Username
	activity.BeforeInsert()

	// 保存到数据库
	id, err := models.CreateCouponActivity(activity)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建优惠活动失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建优惠活动成功",
		"data": map[string]interface{}{
			"id": id,
		},
	}
	c.ServeJSON()
}

// Update 更新优惠活动
func (c *CouponActivityController) Update() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req CouponActivityUpdateRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取优惠活动信息
	activity, err := models.GetCouponActivityById(req.Id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠活动信息失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && activity.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权更新此优惠活动",
		}
		c.ServeJSON()
		return
	}

	// 检查时间有效性
	if req.StartTime <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的开始时间",
		}
		c.ServeJSON()
		return
	}

	if req.EndTime <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的结束时间",
		}
		c.ServeJSON()
		return
	}

	// 处理优惠券ID
	var couponIdsStr string
	if req.Type == 3 && len(req.CouponIds) > 0 {
		couponIdsBytes, err := json.Marshal(req.CouponIds)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "处理优惠券ID失败",
			}
			c.ServeJSON()
			return
		}
		couponIdsStr = string(couponIdsBytes)
	}

	// 更新优惠活动信息
	activity.Name = req.Name
	activity.Type = req.Type
	activity.Description = req.Description
	activity.StartTime = req.StartTime
	activity.EndTime = req.EndTime
	activity.MinAmount = req.MinAmount
	activity.DiscountAmount = req.DiscountAmount
	activity.DiscountRate = req.DiscountRate
	activity.CouponIds = couponIdsStr
	activity.Status = req.Status
	activity.ApplicableType = req.ApplicableType
	activity.ApplicableIds = req.ApplicableIds
	activity.AvailableWeekdays = req.AvailableWeekdays
	activity.AvailableTimes = req.AvailableTimes
	activity.UpdatedBy = permResult.Admin.Username
	activity.UpdatedAt = time.Now().Unix()

	// 保存到数据库
	err = models.UpdateCouponActivity(activity)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新优惠活动失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新优惠活动成功",
	}
	c.ServeJSON()
}

// Delete 删除优惠活动
func (c *CouponActivityController) Delete() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取优惠活动ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的优惠活动ID",
		}
		c.ServeJSON()
		return
	}

	// 获取优惠活动信息
	activity, err := models.GetCouponActivityById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠活动信息失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && activity.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权删除此优惠活动",
		}
		c.ServeJSON()
		return
	}

	// 删除优惠活动
	err = models.DeleteCouponActivity(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "删除优惠活动失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "删除优惠活动成功",
	}
	c.ServeJSON()
}
